package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.ChannelDetailGridAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.ChannelDetailList;
import com.elinkway.infinitemovies.bean.ChannelNewParams;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.SiftKVP;
import com.elinkway.infinitemovies.bean.SubChannelType;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.ChannelDetailListParser;
import com.elinkway.infinitemovies.http.parser.SiftKVPParser;
import com.elinkway.infinitemovies.listener.MyOnRefreshListner;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.MyHorizontalScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ChannelDetailActivity extends BaseActionBarActivity {

	public static final String TAG = "ChannelDetailActivity";

	private final String TV_PLAY = "电视剧";

	private final String MOVIES = "电影";

	private final String CARTOON = "动漫";

	private final String VARIETY = "综艺";

	private final String RECORD = "纪录片";

	private final String HOTEST = "最热";

	private final int FIRST_TAG = 5 << 24;

	private final int SECOND_TAG = 6 << 24;

	private final int THIRD_TAG = 7 << 24;

	private final int FOURTH_TAG = 8 << 24;

	private final String[][] MyFirstFilter = {{"筛选", "追剧", "韩剧", "美剧", "经典"},
			                                  {"筛选", "精选", "美国", "韩国", "日本"},
			                                  {"筛选", "精选", "内地", "日本", "成人"},
			                                  {"筛选", "热播", "真人秀", "搞笑"},
			                                  {"筛选", "口碑推荐", "自然", "历史", "科学"}};
	private final String[][] MyFirstFilterId = {{"", MoviesConstant.LASTEST, MoviesConstant.HOTEST, MoviesConstant.LASTEST, MoviesConstant.GOODPING},
			{"", MoviesConstant.HOTEST, MoviesConstant.HOTEST, MoviesConstant.HOTEST, MoviesConstant.HOTEST},
			{"", MoviesConstant.HOTEST, MoviesConstant.HOTEST, MoviesConstant.HOTEST, MoviesConstant.HOTEST},
			{"", MoviesConstant.LASTEST, MoviesConstant.LASTEST, MoviesConstant.LASTEST},
			{"", MoviesConstant.GOODPING, MoviesConstant.HOTEST, MoviesConstant.HOTEST, MoviesConstant.HOTEST}};
	private final String MyFirstFilterKey = "orderby";
	private final String SecondFilterKey = "area";
	private final String ThirdFilterKey = "year";
	private final String FourthFilterKey = "subcategory";
	private final String[][] MySecondFilterId = {{"", "2016", "50042", "50071", "all"}, {"", "all", "50071", "50042", "50041"},
			{"", "all", "all", "50041", "30089"}, {"", "50001", "30075", "30057"}, {"", "all", "30112", "30153", "30114"}};
	private final String[][] MySecondFilterKey = {{"", "year", "area", "area", "year"}, {"", "area", "area", "area", "area"},
			{"", "year", "year", "area", "subcategory"}, {"", "area", "subcategory", "subcategory"},
			{"", "year", "subcategory", "subcategory", "subcategory"}};
	private ArrayList<SiftKVP> mFirstSubList = null;
	private ArrayList<SiftKVP> mSecondSubList = null;
	private MyHorizontalScrollView mFirstFilterHorizontalView;
	private LinearLayout mFirstFilterLinearLayout;
	private PullToRefreshGridView mGridView;
	private ImageView mTitleBackButton;
	private TextView mTitle;
	private TextView mFilterResultTextView;
	private ChannelDetailGridAdapter mGridAdapter;
	private int scrollViewSelectedItem = 0;
	private String[] channelFilterArray = null;
	private String[] mFirstChannelFilterArray = null;
	private String lastSelectedFilterTxt;
	private String lastFirstSelectedFilterTxt;
	private int mChannelId = 0;
	private String mChannelName;
	private String mTabName;
	private boolean iSInitFilter;
	public int currentPage = 1;
	private ChannelDetailList detailList;
	private RequestChannelDetail requestTask;
	private int popupHeight = 0; // 筛选栏高度 = 筛选项数量 * UIs.dip2px(44);
	/**
	 * 筛选当前选中数组
	 */
	private ArrayList<SiftKVP> siftKVPs;
	/**
	 * 筛选菜单选中或者默认的条件的条件
	 */
	private ArrayList<SiftKVP> mChannelSiftKVPs;
	private TextView[] channelFilterSelectedArray = null;
	private TextView[] mFirstFilterSelectedArray = null;
	private View layoutView;
	private LayoutInflater inflater;
	private SubChannelType mSubChannelType;

	/**
	 * 是否正在请求数据
	 */
	private boolean isRequestData = false;
	private String vt;
	private boolean isSiftShow = false;

	private View loading;
	private ImageView mLoadingIv;
	private AnimationDrawable animationDrawable;
	private View loading_failed;
	private Button btnRefresh;
	private boolean hasMore = true;

	private boolean isGridScrolled = false;
	
	private Handler mHandler = new Handler();
	
	//网络变化广播接收
	private NetworkCheckReceiver mCheckReceiver;
	//是否显示mFilterButton
	private boolean isShowFilterButton;
	//mFilterButton是否可用
	private boolean isEnabled = true;
	private JumpData mJd;
	private boolean mIsSelectDefaultFirstLine;
	private boolean isPgvReported;
	private RequestFiltersTask mRequestFiltersTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setActionBarActivityClassName(TAG);
		setContentView(R.layout.activity_channel_detail);
		initActionBar();
		mFilterResultTextView = (TextView) findViewById(R.id.filter_result);
		mTitleTv.setText("");
		inflater = LayoutInflater.from(this);
		mJd = (JumpData)getIntent().getSerializableExtra(Utils.CHANNEL_DTAT);
		vt=mJd.getVt();
		mChannelName = mJd.getName();
//		mTitleTv.setText(mJd.getName());
		if (MoviesConstant.VT_ZONGYI.equals(vt)) {
			UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_VARIETY, MoviesApplication.getInstance().getLastPageClassName());
		} else if (MoviesConstant.VT_MOVIE.equals(vt)) {
			UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_MOVIES, MoviesApplication.getInstance().getLastPageClassName());
		} else if (MoviesConstant.VT_CARTOON.equals(vt)) {
			UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_CARTOON, MoviesApplication.getInstance().getLastPageClassName());
		} else if (MoviesConstant.VT_TV.equals(vt)) {
			UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_TV_PALY, MoviesApplication.getInstance().getLastPageClassName());
		} else if (MoviesConstant.VT_DOCUMENTARY.equals(vt)) {
			UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_RECORD, MoviesApplication.getInstance().getLastPageClassName());
		}

		LogUtils.e("channel","cate:"+mJd.getCategoryid()+" area:"+mJd.getAreaid() + " " + mChannelName);
		mChannelSiftKVPs = new ArrayList<>();
		mChannelSiftKVPs.add(new SiftKVP(mJd.getChannelNewParams() == null ? "" : mJd.getChannelNewParams().getName(),
				mJd.getChannelNewParams() == null ? MoviesConstant.HOTEST : mJd.getChannelNewParams().getOrderby(),
				MyFirstFilterKey));
		mChannelSiftKVPs.add(new SiftKVP(mJd.getChannelNewParams() == null ? "" : mJd.getChannelNewParams().getName(),
				mJd.getChannelNewParams() == null ? mJd.getAreaid() : mJd.getChannelNewParams().getArea(),
				SecondFilterKey));
		mChannelSiftKVPs.add(new SiftKVP(mJd.getChannelNewParams() == null ? "" : mJd.getChannelNewParams().getName(),
				mJd.getChannelNewParams() == null ? "" : mJd.getChannelNewParams().getYear(),
				ThirdFilterKey));
		mChannelSiftKVPs.add(new SiftKVP(mJd.getChannelNewParams() == null ? "" : mJd.getChannelNewParams().getName(),
				mJd.getChannelNewParams() == null ? mJd.getCategoryid() : mJd.getChannelNewParams().getSubcategory(),
				FourthFilterKey));
		siftKVPs = (ArrayList<SiftKVP>) mChannelSiftKVPs.clone();
		initTitleBar();
		initFirstFilterView();
		initGridView();
		dismissFilterResult();
		mFilterResultTextView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				controlSiftView(mFirstFilterLinearLayout.getChildAt(0));
			}
		});
		layoutView = UIs.inflate(this, R.layout.filter_layout, null);
		TranslateAnimation animTopIn = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, -0.5f,
				Animation.RELATIVE_TO_SELF, 0.0f);
		animTopIn.setDuration(300);
		layoutView.setAnimation(animTopIn);
		initLoading();
		mRequestFiltersTask = new RequestFiltersTask(getApplicationContext(), true);
		mRequestFiltersTask.start();
		requestChannelData(true);
		setOnLoading();
	}

	@Override
	protected void initActionBar(){
		super.initActionBar();
		mRightSecondIv.setImageResource(R.drawable.download_icon_bb_selector);
		mRightSecondIv.setVisibility(View.VISIBLE);
		mRightSecondIv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(ChannelDetailActivity.this,
						DownloadActivity.class);
				startActivity(intent);
			}
		});
		mRightFirstIv.setImageResource(R.drawable.search_icon_bb_selector);
		mRightFirstIv.setVisibility(View.VISIBLE);
		mRightFirstIv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				SearchActivity.launch(ChannelDetailActivity.this);
			}
		});
	}

	private void initTitleBar() {
		mTitleBackButton = (ImageView) findViewById(R.id.channel_detail_topbar_back);
		mTitle = (TextView) findViewById(R.id.channel_detail_topbar_title);
		mTitleBackButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	private void CreateKVP() {
		mFirstSubList = new ArrayList<>();
		mSecondSubList = new ArrayList<>();
		int i = getPosition();
		for (int j = 0; j < MyFirstFilter[i].length; j++) {
			SiftKVP tempKvp = new SiftKVP(MyFirstFilter[i][j], MyFirstFilterId[i][j],
					MyFirstFilterKey);
			mFirstSubList.add(tempKvp);
			SiftKVP tempKvp2 = new SiftKVP(MyFirstFilter[i][j], MySecondFilterId[i][j],
					MySecondFilterKey[i][j]);
			mSecondSubList.add(tempKvp2);
		}
	}

	private void initFirstFilterView() {
		if (mChannelName == null || iSInitFilter) {
			return;
		}
		iSInitFilter = true;
		mFirstFilterHorizontalView = (MyHorizontalScrollView) findViewById(R.id.hsv_first_filter_scrollview);
		mFirstFilterLinearLayout = (LinearLayout) findViewById(R.id.ll_first_filter_options);
		mFirstFilterLinearLayout.removeAllViews();
		CreateKVP();
		mFirstChannelFilterArray = new String[1];
		mFirstFilterSelectedArray = new TextView[1];
		int j = getPosition();
		if (j < 0) {
			return;
		}

			for(int i = 0; i < MyFirstFilter[j].length; i++) {
				LinearLayout tempLayout = (LinearLayout) inflater.inflate(
						R.layout.filter_options_item, mFirstFilterHorizontalView, false);
				TextView tempTextView = (TextView) tempLayout
						.findViewById(R.id.text);
				if (i == 1 && mJd.getChannelNewParams() != null) {
					tempTextView.setTag(new SiftKVP(mJd.getChannelNewParams().getName(), "jump", ""));
					if (!TextUtils.isEmpty(mJd.getChannelNewParams().getOrderby())) {
						tempTextView.setTag(FIRST_TAG, new SiftKVP(mJd.getChannelNewParams().getName(), mJd.getChannelNewParams().getOrderby(),
								MyFirstFilterKey));
					}
					if (!TextUtils.isEmpty(mJd.getChannelNewParams().getArea())) {
						tempTextView.setTag(SECOND_TAG, new SiftKVP(mJd.getChannelNewParams().getName(), mJd.getChannelNewParams().getArea(),
								SecondFilterKey));
					}
					if (!TextUtils.isEmpty(mJd.getChannelNewParams().getYear())) {
						tempTextView.setTag(THIRD_TAG, new SiftKVP(mJd.getChannelNewParams().getName(), mJd.getChannelNewParams().getYear(),
								ThirdFilterKey));
					}
					if (!TextUtils.isEmpty(mJd.getChannelNewParams().getSubcategory())) {
						tempTextView.setTag(FOURTH_TAG, new SiftKVP(mJd.getChannelNewParams().getName(), mJd.getChannelNewParams().getSubcategory(),
								FourthFilterKey));
					}
					mTabName = mJd.getChannelNewParams().getName();
					tempTextView.setText(mJd.getChannelNewParams().getName());
					tempTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.len_15dp));
					tempTextView.setPadding(getResources().getDimensionPixelOffset(R.dimen.len_15dp), 0, getResources().getDimensionPixelOffset(R.dimen.len_15dp), 0);
					mIsSelectDefaultFirstLine = true;
					mFirstFilterSelectedArray[0] = tempTextView;
					mFirstChannelFilterArray[0] = "jump";
					lastFirstSelectedFilterTxt = mJd.getChannelNewParams().getName();
					mFirstFilterSelectedArray[0]
							.setTextColor(ChannelDetailActivity.this
									.getResources().getColor(
											R.color.color_ff00a0e9));
					createFilterConditionProcess(
							mFirstFilterSelectedArray, true);
					mJd.setChannelNewParams(null);
					i--;
				} else {
					tempTextView.setTag(mFirstSubList.get(i));
					tempTextView.setTag(FIRST_TAG, mFirstSubList.get(i));
					tempTextView.setTag(SECOND_TAG, mSecondSubList.get(i));
					tempTextView.setText(MyFirstFilter[j][i]);
					tempTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.len_15dp));
					tempTextView.setPadding(getResources().getDimensionPixelOffset(R.dimen.len_15dp), 0, getResources().getDimensionPixelOffset(R.dimen.len_15dp), 0);
				}
				mFirstFilterLinearLayout.addView(tempLayout);
                if (i == 1 && !mIsSelectDefaultFirstLine) { //默认选中第一个
					mIsSelectDefaultFirstLine = true;
					mFirstFilterSelectedArray[0] = tempTextView;
					mFirstChannelFilterArray[0] = mFirstSubList.get(1).getId();
					lastFirstSelectedFilterTxt = mFirstSubList.get(1).getKey();
					mFirstFilterSelectedArray[0]
							.setTextColor(ChannelDetailActivity.this
									.getResources().getColor(
											R.color.color_ff00a0e9));
					createFilterConditionProcess(
							mFirstFilterSelectedArray, true);
				}
				tempTextView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						LogUtils.e(TAG, "onClick " + ((SiftKVP) v.getTag()).getId() + " "
								+ ((SiftKVP) v.getTag()).getKey() + " " + mFirstChannelFilterArray[0] + " "
								+ lastFirstSelectedFilterTxt);
						SiftKVP kvp = (SiftKVP) v.getTag();
						mTabName = kvp.getKey();
						if ("筛选".equals(kvp.getKey())) {
							mFirstFilterSelectedArray[0]
									.setTextColor(ChannelDetailActivity.this
											.getResources().getColor(
													R.color.color_ff393939));
							mFirstChannelFilterArray[0] = "";
							lastFirstSelectedFilterTxt = "筛选";
							mFirstFilterSelectedArray[0] = (TextView) v;
							mFirstFilterSelectedArray[0]
									.setTextColor(ChannelDetailActivity.this
											.getResources().getColor(
													R.color.color_ff00a0e9));
							displayFilterResult();
							controlSiftView(v);

						} else if (!kvp.getId().equals(mFirstChannelFilterArray[0])
								|| !kvp.getKey().equalsIgnoreCase(
								lastFirstSelectedFilterTxt)) {
							if (isPopWinShow()) {
								unDiplayControlSift();
							}
							mFilterResultTextView.setVisibility(View.GONE);
							mFirstFilterSelectedArray[0]
									.setTextColor(ChannelDetailActivity.this
											.getResources().getColor(
													R.color.color_ff393939));
							mFirstFilterSelectedArray[0] = (TextView) v;
							mFirstFilterSelectedArray[0]
									.setTextColor(ChannelDetailActivity.this
											.getResources().getColor(
													R.color.color_ff00a0e9));
							mFirstChannelFilterArray[0] = kvp.getId();
							lastFirstSelectedFilterTxt = kvp.getKey();

							Map<String, String> dataMap = BigDataApi.createDataMap("0", "subtitle=" + lastFirstSelectedFilterTxt,"0","-","","-");
							dataMap.put("cur_url", currentPageId);
							BigDataApi.bigDataCommonReport(dataMap, ChannelDetailActivity.this);

							// LogInfo.log("home",
							// "channelFilterArray[index]= "+channelFilterArray[index]+"  lastSelectedFilterTxt ="+lastSelectedFilterTxt);
							createFilterConditionProcess(
									mFirstFilterSelectedArray, true);
							isRequestData = true;
							requsetData();
						}
						MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
						if (VARIETY.equals(mChannelName)) {
							record.setCur_url("variety");
						} else if (MOVIES.equals(mChannelName)) {
							record.setCur_url("movie");
						} else if (CARTOON.equals(mChannelName)) {
							record.setCur_url("cartoon");
						} else if (TV_PLAY.equals(mChannelName)) {
							record.setCur_url("episodes");
						} else if (RECORD.equals(mChannelName)) {
							record.setCur_url("documentary");
						}

						record.setAp("tag");
						record.setAcode("0");
						record.setTag_name(kvp.getKey());
						RealmDaoManager.addMyDataRecord(record);
					}
				});
		}

	}

	private void initGridView() {
		mGridView = (PullToRefreshGridView) findViewById(R.id.channel_detail_grid);
		mGridAdapter = new ChannelDetailGridAdapter(this,
				new ChannelDetailList());
		mGridView.setAdapter(mGridAdapter);
		mGridView.getRefreshableView().setOnTouchListener(new OnTouchListener() {
			private float mInitialX;
			private float mInitialY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mInitialX = event.getX();
					mInitialY = event.getY();
					break;
				case MotionEvent.ACTION_MOVE:
					final float x = event.getX();
					final float y = event.getY();
					final float yDiff = y - mInitialY;
					if (yDiff < 0.0) {
						unDiplayControlSift();
						displayFilterResult();
						if (mFilterResultTextView != null &&
								mFilterResultTextView.getVisibility() == View.GONE) {
							mGridView.setPadding(0, 0, 0 ,0);
						}
					}
					break;
				}
				return false;
			}
		});

		mGridView.setOnRefreshListener(new ChannelOnRefreshListener());
		resetHasMore();
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
				if (VARIETY.equals(mChannelName)) {
					record.setCur_url("variety");
				} else if (MOVIES.equals(mChannelName)) {
					record.setCur_url("movie");
				} else if (CARTOON.equals(mChannelName)) {
					record.setCur_url("cartoon");
				} else if (TV_PLAY.equals(mChannelName)) {
					record.setCur_url("episodes");
				} else if (RECORD.equals(mChannelName)) {
					record.setCur_url("documentary");
				}
				record.setAp("works area");
				record.setAcode("0");
				record.setTag_name(mTabName);
				LogUtils.d("channelD", "mTabName is:" + mTabName);
				RealmDaoManager.addMyDataRecord(record);
				// TODO Auto-generated method stub
				LogUtils.i("channelGrid", "click position " + position);
				String aid = detailList.getChannelDetails().get(position)
						.getAid();
				String title = detailList.getChannelDetails().get(position)
						.getName();
				String src = detailList.getChannelDetails().get(position)
						.getSrc();
				VideoDetailActivity.launch(ChannelDetailActivity.this, aid, vt,
						title, src, "", "", "0","","");
			}
		});
		mGridView.getRefreshableView().requestFocus();
	}

	private void initLoading() {
		loading = findViewById(R.id.channel_loading);
		mLoadingIv = (ImageView) findViewById(R.id.loading_progressBar);
		loading_failed = findViewById(R.id.channel_loading_failed);
	}

	private void setLoadingFailed() {
		currentPage = 1;
		loading.setVisibility(View.GONE);
		animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
		animationDrawable.stop();
		mGridView.setVisibility(View.GONE);
		loading_failed.setVisibility(View.VISIBLE);
//		mFilterButton.setVisibility(View.GONE);
		setFilterButtonState(false,isEnabled);
		unDiplayControlSift();
		btnRefresh = (Button) loading_failed.findViewById(R.id.bn_refresh);
		btnRefresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (requestTask != null) {
					requestTask.cancel();
				}
				currentPage = 1;
				requestTask = new RequestChannelDetail(
						ChannelDetailActivity.this, true, true);
				requestTask.start();
				mRequestFiltersTask = new RequestFiltersTask(getApplicationContext(), false);
				mRequestFiltersTask.start();
				setOnLoading();
			}
		});
	}

	private void setOnLoading() {
//		mFilterButton.setEnabled(false);
		setFilterButtonState(isShowFilterButton,false);
		loading.setVisibility(View.VISIBLE);
		animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
		animationDrawable.start();
		mGridView.setVisibility(View.GONE);
		loading_failed.setVisibility(View.GONE);
	}

	private void setLoadingComplete() {
//		mFilterButton.setEnabled(true);
		setFilterButtonState(true,true);
		loading.setVisibility(View.GONE);
		animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
		animationDrawable.stop();
		mGridView.setVisibility(View.VISIBLE);
		loading_failed.setVisibility(View.GONE);
//		mFilterButton.setVisibility(View.VISIBLE);
	}

	public static void launch(Activity activity, String vt, String title, ChannelNewParams params) {
		Intent intent = new Intent(activity, ChannelDetailActivity.class);
		JumpData jd = new JumpData();
		jd.setVt(vt);
		jd.setName(title);
		jd.setChannelNewParams(params);
		jd.setAreaid("all");
		jd.setCategoryid("all");
		Bundle bundle = new Bundle();
		bundle.putSerializable(Utils.CHANNEL_DTAT, jd);
		intent.putExtras(bundle);
		activity.startActivity(intent);
	}

	private void createFilterLayout(View filterLayout, boolean isFirst) {
		if (filterLayout == null) {
			return;
		}
		mPopupWindow = new PopupWindow(filterLayout,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		// 如果希望点击其他的位置popupwindow自动消失必须设置这两项： 1 setFoucable(true) 2
		// setBackground();
		mPopupWindow.setFocusable(false);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		LinearLayout filterBody = (LinearLayout) filterLayout
				.findViewById(R.id.filter_body);
		filterBody.removeAllViews();
		int count = mSubChannelType.getCount();
		channelFilterArray = null;
		channelFilterSelectedArray = null;
		channelFilterArray = new String[count];
		channelFilterSelectedArray = new TextView[count];
		ArrayList<SiftKVP> channelSubList = null;
		LogUtils.e(TAG, "count is " + count);
		for (int i = 0; i < count; i++) {
			channelSubList = mSubChannelType.getChannelSubList(i);
			final int index = i;
			if (channelSubList != null && channelSubList.size() > 0) {

				RelativeLayout siftView = (RelativeLayout) inflater.inflate(
						R.layout.filter_layout_item, filterBody, false);
				siftView.setVisibility(View.VISIBLE);

				final MyHorizontalScrollView scrollView = (MyHorizontalScrollView) siftView
						.findViewById(R.id.filter_scrollview);
				LinearLayout options = (LinearLayout) siftView
						.findViewById(R.id.filter_options);
				scrollView.setScreenWidth(UIs.getScreenWidth());
				SiftKVP kvp = null;
				final int csListSize = channelSubList.size();
				for (int j = 0; j < csListSize; j++) {
					final int mCurrentPosition = j;
					kvp = channelSubList.get(j);
					LinearLayout layout = (LinearLayout) inflater.inflate(
							R.layout.filter_options_item, filterBody, false);
					TextView textView = (TextView) layout
							.findViewById(R.id.text);

					textView.setTag(kvp);
					textView.setText(kvp.getKey());

					options.addView(layout);

					textView.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							SiftKVP kvp = (SiftKVP) v.getTag();
							if (!kvp.getId().equals(channelFilterArray[index])
									|| !kvp.getKey().equalsIgnoreCase(
											lastSelectedFilterTxt)) {
								channelFilterSelectedArray[index]
										.setTextColor(ChannelDetailActivity.this
												.getResources().getColor(
														R.color.color_ff393939));
								channelFilterSelectedArray[index] = (TextView) v;
								channelFilterSelectedArray[index]
										.setTextColor(ChannelDetailActivity.this
												.getResources().getColor(
														R.color.color_ff00a0e9));
								scrollToSecond(scrollView, (View)v.getParent(), mCurrentPosition);
								channelFilterArray[index] = kvp.getId();
								lastSelectedFilterTxt = kvp.getKey();
								if (siftKVPs != null) {// 初始化一次就清除
									siftKVPs.clear();
									siftKVPs = null;
								}
								// LogInfo.log("home",
								// "channelFilterArray[index]= "+channelFilterArray[index]+"  lastSelectedFilterTxt ="+lastSelectedFilterTxt);
								createFilterConditionProcess(
										channelFilterSelectedArray, false);
								isRequestData = true;
								requsetData();
							}
						}
					});
					if (j == 0) {
						channelFilterArray[index] = kvp.getId();
						if (channelFilterSelectedArray[index] == null) {
							channelFilterSelectedArray[index] = textView;
						}
						channelFilterSelectedArray[index].setTextColor(this
								.getResources()
								.getColor(R.color.color_ff00a0e9));
					}
					if (siftKVPs != null && siftKVPs.size() > 0) {
						for (SiftKVP kvpTmp : siftKVPs) {
							if ((kvpTmp.getFilterKey().equals(
									kvp.getFilterKey()) || kvpTmp
									.getFilterKey().equals(kvp.getKeyReplace()))
									&& kvpTmp.getId().equals(kvp.getId())) {
								channelFilterArray[index] = kvp.getId();
								lastSelectedFilterTxt = kvp.getKey();
								break;
							}
						}
					}
					if (kvp.getId().equals(channelFilterArray[index])) {
						scrollViewSelectedItem = j;
						if (channelFilterSelectedArray[index] != null) {
							channelFilterSelectedArray[index].setTextColor(this
									.getResources().getColor(
											R.color.color_ff393939));
						}
						channelFilterSelectedArray[index] = textView;
						channelFilterSelectedArray[index].setTextColor(this
								.getResources()
								.getColor(R.color.color_ff00a0e9));
					}
				}
				if (i < count) {
					ImageView imageView = new ImageView(this);
					LayoutParams layoutParams = new LayoutParams(
							LayoutParams.MATCH_PARENT, 1);
					imageView.setLayoutParams(layoutParams);
					imageView.setPadding(UIs.dipToPx(12), 0, 0, 0);
					imageView.setBackgroundResource(R.color.color_ffdfdfdf);
					filterBody.addView(imageView);
				}

				filterBody.addView(siftView);
			}

		}
		if (isFirst) {
			return;
		}
		createFilterConditionProcess(channelFilterSelectedArray, false);
	}

	/**
	 * 创建筛选条件
	 *
	 * @param channelFilterSelectedArray
	 * @param isFirst
	 *            是否是第一次创建
	 */
	private void createFilterConditionProcess(
			TextView[] channelFilterSelectedArray, boolean isFirstLine) {
		if (channelFilterSelectedArray != null
				&& channelFilterSelectedArray.length > 0) {
			SiftKVP kvp = null;
			SiftKVP secondKvp;
			SiftKVP thirdKvp;
			SiftKVP fourKvp;
			TextView textView = null;
			if (mChannelSiftKVPs == null) {
				mChannelSiftKVPs = new ArrayList<SiftKVP>();
			}
			mChannelSiftKVPs.clear();
			for (int i = 0; i < channelFilterSelectedArray.length; i++) {
				textView = channelFilterSelectedArray[i];
				if (isFirstLine) {
					kvp = (SiftKVP) textView.getTag(FIRST_TAG);
					secondKvp = (SiftKVP) textView.getTag(SECOND_TAG);
					thirdKvp = (SiftKVP) textView.getTag(THIRD_TAG);
					fourKvp = (SiftKVP) textView.getTag(FOURTH_TAG);
					if (kvp != null) {
						mChannelSiftKVPs.add(kvp);
					}
					if (secondKvp != null) {
						mChannelSiftKVPs.add(secondKvp);
					}
					if (thirdKvp != null) {
						mChannelSiftKVPs.add(thirdKvp);
					}
					if (fourKvp != null) {
						mChannelSiftKVPs.add(fourKvp);
					}
				} else {
					kvp = (SiftKVP) textView.getTag();
					if (kvp != null) {
						mChannelSiftKVPs.add(kvp);
					}
				}
			}
		}
	}

	/**
	 * 筛选window是否初始化成功
	 * 
	 * @return
	 */
	public boolean isFilterReady() {
		if (mSubChannelType == null || mSubChannelType.getCount() <= 0) {
			return false;
		}
		return true;
	}

	private void displayFilterResult() {
		String text = "";
		if (channelFilterSelectedArray == null) {
			return;
		}
		for (int i = 0; i < channelFilterSelectedArray.length; i++) {
			LogUtils.e(TAG, "SiftKVp tag is " + ((SiftKVP)(channelFilterSelectedArray[i].getTag())).getId());
			if (!"all".equals(((SiftKVP)(channelFilterSelectedArray[i].getTag())).getId())) {
				text = text  + '·';
				text = text + (channelFilterSelectedArray[i].getText());
			}
		}
		text = text.substring(1);
		if (mFilterResultTextView != null && !HOTEST.equals(text)) {
			mGridView.setPadding(0, UIs.dipToPx(20), 0 ,0);
			mFilterResultTextView.setVisibility(View.VISIBLE);
			mFilterResultTextView.setText(text);
		} else if (mFilterResultTextView != null){
			mFilterResultTextView.setVisibility(View.GONE);
		}
	}

	private void dismissFilterResult() {
		if (mFilterResultTextView != null) {
			mFilterResultTextView.setVisibility(View.GONE);
		}
	}


	/**
	 * 显示筛选栏
	 */
	private void diplayControlSift(View v) {
		// 显示筛选栏动画
		if (mPopupWindow != null && !mPopupWindow.isShowing()) {
			showPopWindowForView(v);
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				mGridView.setY(popupHeight);
			} else {
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.MATCH_PARENT,
						RelativeLayout.LayoutParams.MATCH_PARENT);
				params.setMargins(0,popupHeight, 0, 0);
				mGridView.setLayoutParams(params);
			}
			isSiftShow = true;
		}
	}

	private boolean isPopWinShow() {
		if (mPopupWindow != null) {
			return mPopupWindow.isShowing();
		} else {
			return false;
		}
	}

	/**
	 * 隐藏筛选栏
	 */
	public void unDiplayControlSift() {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			// 隐藏筛选栏动画
			mPopupWindow.dismiss();
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				mGridView.setY(UIs.dipToPx(62));
			} else {
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.MATCH_PARENT,
						RelativeLayout.LayoutParams.MATCH_PARENT);
				params.setMargins(0,UIs.dipToPx(62), 0, 0);
				mGridView.setLayoutParams(params);
			}
			isSiftShow = false;
		}
	}

	private void requsetData() {
		mGridView.requestFocus();
		mGridView.getRefreshableView().smoothScrollToPosition(0);
		LogUtils.e(TAG, "mChannelSiftKVP size is " + mChannelSiftKVPs.size());
		updateFilterData(vt, mChannelSiftKVPs);
	}

	private void updateFilterData(String vt2, ArrayList<SiftKVP> channelSiftKVPs) {
		// TODO Auto-generated method stub
		if (requestTask != null) {
			requestTask.cancel();
		}
		requestTask = new RequestChannelDetail(this, true, true);
		requestTask.start();
	}

	// ===================================================
	private PopupWindow mPopupWindow;

	private void showPopWindowForView(View view) {
		TranslateAnimation animTopIn = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, -0.5f,
				Animation.RELATIVE_TO_SELF, 0.0f);
		animTopIn.setDuration(300);
		layoutView.setAnimation(animTopIn);
		int[] arrayOfInf = new int[2];
		view.getLocationInWindow(arrayOfInf);
		int x = arrayOfInf[0];
		int y = arrayOfInf[1];
	    int yoffSet = (int) UIs.dipToPxFloat(30);
		y = y + yoffSet;
		mPopupWindow.setAnimationStyle(R.style.popwin_anim_style);
		if (!this.isFinishing()) {
			mPopupWindow.showAtLocation(view, Gravity.TOP | Gravity.LEFT, x, y);
		}

	}

	public void controlSiftView(View v) {
		boolean isShow = isPopWinShow();
		if (!isShow) {
			diplayControlSift(v);
		} else {
			unDiplayControlSift();
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		if (isSiftShow) {
			diplayControlSift(mRightFirstTv);
		}
		super.onStart();
	}
	private class OnChannelGridScrollListener implements OnScrollListener {
		private int lastVisibleIndex;

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
					&& lastVisibleIndex == mGridAdapter.getCount()
					) {
			}

		}
	}

	// 请求数据任务
	private class RequestChannelDetail extends
			MoviesHttpAsyncTask<ChannelDetailList> {
		private int requestPage = 1;
		private boolean isRefresh = false;
		private boolean needLoading = false;

		public RequestChannelDetail(Context context, boolean needLoading,
				boolean isRefresh) {
			super(context);
			if (isRefresh) {
				requestPage = 1;
			} else {
				requestPage = currentPage;
			}
			this.isRefresh = isRefresh;
			this.needLoading = needLoading;
			if (needLoading) {
				setOnLoading();
			}
		}

		@Override
		public LVideoDataHull<ChannelDetailList> doInBackground() {
			// TODO Auto-generated method stub
			return requestDataByFilter(requestPage, mChannelSiftKVPs);
		}

		/**
		 * 获得数据后操作
		 */
		@Override
		public void onPostExecute(int updateId, ChannelDetailList result) {
			// TODO Auto-generated method stub
			mTitle.setText(result.getName());
			mTitleTv.setText(result.getName());
			mChannelName = result.getName();
			setCurrentPageId();
			if(!isPgvReported){
				Map<String, String> pgvMap= new HashMap<String, String>();
				pgvMap.put(BigDataApi.REF,MoviesApplication.getInstance().getmPgvLastPageId());
				BigDataApi.bigDataPageShowReport(currentPageId, pgvMap, ChannelDetailActivity.this);
				isPgvReported = true;
			}
			initFirstFilterView();
			// 如果adapter为null，创建. 否则如果是刷新则重新render数据，如果不是刷新添加数据。如果需要loading动画（如第一次进入），则显示loading动画
			if (mGridAdapter == null) {
				mGridAdapter = new ChannelDetailGridAdapter(
						getApplicationContext(), detailList);
				mGridView.setAdapter(mGridAdapter);
				mGridView.onRefreshComplete();
			} 
			else {
				if (!isRefresh) {
					final int currSize = mGridAdapter.getCount();
					mGridAdapter.addItem_data(result);
					mGridView.getRefreshableView().smoothScrollBy(mGridView.footerSize(),500);
					mGridView.onRefreshComplete();
//					mGridView.postDelayed(new Runnable() {
//						
//						@Override
//						public void run() {
//							mGridView.getRefreshableView().smoothScrollToPositionFromTop(currSize, mGridView.footerSize(),200);
//						}
//					}, 50L);
					
				} else {
					currentPage = 1;
					detailList = result;
					mGridAdapter.setItem_data(detailList);
					mGridView.onRefreshComplete();
				}
				currentPage += 1;
				mGridAdapter.notifyDataSetChanged();
				setLoadingComplete();
				// 如果获得数据条数小于请求数据条数，则视为没有更多
				if (result.getChannelDetails().size() < MoviesConstant.CHANNEL_DETAIL_LIST_REQUEST_SIZE) {
					setNoMore(requestPage);

				} else {
					mGridView.setMode(Mode.BOTH);
				}

			}

		}

		@Override
		public void netNull() {
			// TODO Auto-generated method stub
			super.netNull();
			if (needLoading) {
				currentPage = 1;
				setLoadingFailed();
			} else {
				UIs.showToast(R.string.net_error);
			}
			mGridView.onRefreshComplete();
		}

		@Override
		public void netErr(int updateId, String errMsg) {
			// TODO Auto-generated method stub
			super.netErr(updateId, errMsg);
			if (needLoading) {
				currentPage = 1;
				setLoadingFailed();
			} else {
				UIs.showToast(R.string.net_error);
			}
			mGridView.onRefreshComplete();
		}

		private LVideoDataHull<ChannelDetailList> requestDataByFilter(
				int requestPage, ArrayList<SiftKVP> filters) {
			String year = "";
			String subCategory = "";
			String area = "";
			String orderBy = "3";
			if (filters != null) {
				for (SiftKVP kvp : filters) {
					if ("all".equals(kvp.getId())) {
						LogUtils.e(TAG, "filter all " + kvp.getId());
						continue;
					}
					if ("year".equals(kvp.getFilterKey())) {
						LogUtils.e(TAG, "filter year " + kvp.getFilterKey() + " " + kvp.getId());
						year = kvp.getId();
					} else if ("subcategory".equals(kvp.getFilterKey())) {
						LogUtils.e(TAG, "filter subcategory " + kvp.getFilterKey() + " " + kvp.getId());
						subCategory = kvp.getId();
					} else if ("area".equals(kvp.getFilterKey())) {
						LogUtils.e(TAG, "filter area " + kvp.getFilterKey() + " " + kvp.getId());
						area = kvp.getId();
					} else if ("orderby".equals(kvp.getFilterKey())) {
						LogUtils.e(TAG, "filter orderby " + kvp.getFilterKey() + " " + kvp.getId());
						orderBy = kvp.getId();
					}
				}
			}
			return MoviesHttpApi.requestChannelDetail(
					new ChannelDetailListParser(), orderBy, requestPage,
					subCategory,
					MoviesConstant.CHANNEL_DETAIL_LIST_REQUEST_SIZE, area, vt,
					year);
		}
	}

	private class ChannelOnRefreshListener extends MyOnRefreshListner {

		@Override
		public void onLoadMoreData() {
			if (hasMore) {
				if (requestTask != null) {
					if (!requestTask.isCancelled()) {
						requestTask.cancel();
						requestTask = null;
					}
				}
				requestTask = new RequestChannelDetail(getApplicationContext(),
						false, false);
				requestTask.start();
			} else {
				mGridView.onRefreshComplete();
			}
		}

		@Override
		protected void onRefreshData() {
			// TODO Auto-generated method stub
			if (requestTask != null) {
				if (!requestTask.isCancelled()) {
					requestTask.cancel();
					requestTask = null;
				}
			}
			requestTask = new RequestChannelDetail(getApplicationContext(),
					false, true);
			requestTask.start();
		}

	}

	private class RequestFiltersTask extends MoviesHttpAsyncTask<SubChannelType> {

		boolean mFirst;
		public RequestFiltersTask(Context context, boolean isFirst) {
			super(context);
			mFirst = isFirst;
		}

		@Override
		public LVideoDataHull<SubChannelType> doInBackground() {
			return MoviesHttpApi.requestSiftList(new SiftKVPParser(), vt);
		}

		@Override
		public void onPostExecute(int updateId, SubChannelType result) {
			mSubChannelType = result;
			createFilterLayout(layoutView, mFirst);
			popupHeight = (mSubChannelType.getCount() + 1 ) * UIs.dipToPx(44);
		}

		@Override
		public void netNull() {
			super.netNull();
		}

		@Override
		public void netErr(int updateId, String errMsg) {
			super.netErr(updateId, errMsg);
			mRightFirstTv.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
				}
			});
		}
	}

	private void requestChannelData(boolean needLoading) {
		if (requestTask != null) {
			requestTask.cancel();
		}
		requestTask = new RequestChannelDetail(getApplicationContext(), needLoading, true);
		requestTask.start();
	}

	private void setNoMore(int requestPage) {
		hasMore = false;
		if (requestPage == 1) {
			mGridView.setMode(Mode.DISABLED);
		}
		mGridView.setLoadingDrawable(
				getResources().getDrawable(R.drawable.transparent),
				Mode.PULL_UP_TO_REFRESH);
		mGridView.setRefreshingLabel("没有更多了", Mode.PULL_UP_TO_REFRESH);
		mGridView.setReleaseLabel("没有更多了", Mode.PULL_UP_TO_REFRESH);
		mGridView.setPullLabel("没有更多了", Mode.PULL_UP_TO_REFRESH);
	}

	private void resetHasMore() {
		hasMore = true;
		mGridView.setMode(Mode.BOTH);
		mGridView.setLoadingDrawable(
				getResources().getDrawable(R.drawable.default_ptr_rotate),
				Mode.PULL_UP_TO_REFRESH);
		mGridView.setRefreshingLabel("正在载入", Mode.PULL_UP_TO_REFRESH);
		mGridView.setReleaseLabel("松开加载更多", Mode.PULL_UP_TO_REFRESH);
		mGridView.setPullLabel("上拉加载更多", Mode.PULL_UP_TO_REFRESH);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		if (isSiftShow) {
			diplayControlSift(mRightFirstIv);
		}
		super.onResume();
		MobclickAgent.onResume(this);
		registerCheckNetwork();
	}

	@Override
	protected void onDestroy() {
		if (isPopWinShow()) {
			mPopupWindow.dismiss();
		}
		super.onDestroy();
		if (mRequestFiltersTask != null) {
			mRequestFiltersTask.cancel();
			mRequestFiltersTask = null;
		}
	}

	@Override
	public void onBackPressed() {
		if (isPopWinShow()) {
			unDiplayControlSift();
		} else {
			finish();
		}
	}
	
	
	
	
	/**
	 * 
	 * qinguoli
	 * 注册监听手机网络广播 接收
	 */
	protected void registerCheckNetwork() {
		mCheckReceiver = new NetworkCheckReceiver();
		IntentFilter intentfilter = new IntentFilter();
		intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
		intentfilter.addAction(Utils.SDCARD_NOSPACE_ACTION);
		this.registerReceiver(mCheckReceiver, intentfilter);
	}

	/**
	 * qinguoli
	 * 取消对网络变化的监听*
	 */
	protected void unregisterCheckNetwork() {
		if (mCheckReceiver != null) {
			try {
				this.unregisterReceiver(mCheckReceiver);
			} catch (IllegalArgumentException e) {
				if (e.getMessage().contains("Receiver not registered")) {
					LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
					// Ignore this exception. This is exactly what is desired
				} else {
					// unexpected, re-throw
					throw e;
				}
			}
		}
	}
	
	/**
	 * qinguoli
	 * 网络广播监听*
	 */
	class NetworkCheckReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				if(intent.getAction().equals(PlayerUtils.CONNECTIVTY_CHANGE)){
					//读取保存的之前网络状态
					SharedPreferences priorNetState= getSharedPreferences("priornetstate", 
							Activity.MODE_PRIVATE); 
					
					int priorNetType = priorNetState.getInt("netstate", 2);
					
					int nowNetType = NetWorkTypeUtils.checkNet(intent, priorNetType);
					
					
					
					SharedPreferences.Editor editor = priorNetState.edit(); 
					
					editor.putInt("netstate", nowNetType);
					editor.commit();
				}
				if(intent.getAction().equals(Utils.SDCARD_NOSPACE_ACTION)){
					DialogUtil.getInstance(ChannelDetailActivity.this).checkSDCardSpaceDialog();
				}
				
			}
		}
	}
	/**
	 * @param isShowFilterButton 是否显示
	 * @param isEnable 是否可用
	 */
	private void setFilterButtonState(boolean isShowFilterButton,boolean isEnable){
		this.isShowFilterButton = isShowFilterButton;
		this.isEnabled = isEnable;
		if(isShowFilterButton){
			mRightFirstTv.setVisibility(View.GONE);
		}else{
			mRightFirstTv.setVisibility(View.GONE);
		}
	}
	@Override
    protected void onStop() {
        super.onStop();
        unregisterCheckNetwork();
    }

	@Override
	public void dealWithUmeng() {
		LogUtils.i(TAG, "dealWithUmeng " + mChannelName);
		if (VARIETY.equals(mChannelName)) {
			UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_VARIETY);
		} else if (MOVIES.equals(mChannelName)) {
			UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_MOVIES);
		} else if (CARTOON.equals(mChannelName)) {
			UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_CARTOON);
		} else if (TV_PLAY.equals(mChannelName)) {
			UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_TV_PALY);
		} else if (RECORD.equals(mChannelName)) {
			UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_RECORD);
		}
	}

	@Override
	public void dealWithVisitUmeng() {

	}

	public int getPosition() {
		if (TV_PLAY.equals(mChannelName)) {
			return 0;
		} else if (MOVIES.equals(mChannelName)) {
			return 1;
		} else if (CARTOON.equals(mChannelName)) {
			return 2;
		} else if (VARIETY.equals(mChannelName)) {
			return 3;
		} else if (RECORD.equals(mChannelName)) {
			return 4;
		}
		return 0;
	}

	public void scrollToSecond(MyHorizontalScrollView scrollView, View view, int position) {
        int scrollX = view.getLeft();
		LinearLayout parentView = (LinearLayout) view.getParent();
		if (position > 0) {
			scrollX -= parentView.getChildAt(position -1).getWidth();
		}
		scrollView.smoothScrollTo(scrollX, 0);
	}

	private void setCurrentPageId() {
		if (VARIETY.equals(mChannelName)) {
			currentPageId = BigDataConstants.PGV_CURRENT_ID_VARIETY;
		} else if (MOVIES.equals(mChannelName)) {
			currentPageId = BigDataConstants.PGV_CURRENT_ID_MOVIE;
		} else if (CARTOON.equals(mChannelName)) {
			currentPageId = BigDataConstants.PGV_CURRENT_ID_CARTOON;
		} else if (TV_PLAY.equals(mChannelName)) {
			currentPageId = BigDataConstants.PGV_CURRENT_ID_EPISODES;
		} else if (RECORD.equals(mChannelName)) {
			currentPageId = BigDataConstants.PGV_CURRENT_ID_DOCUMENTARY;
		}
	}

}
